package com.neardrug.controller;

import com.neardrug.common.OnlineUserManager;
import com.neardrug.common.Result;
import com.neardrug.context.BaseContext;
import com.neardrug.controller.dto.UserDTO;
import com.neardrug.controller.dto.UserLoginDTO;
import com.neardrug.controller.dto.UserResetDTO;
import com.neardrug.entity.User;
import com.neardrug.properties.JwtProperties;
import com.neardrug.services.UserService;
import com.neardrug.utils.JwtUtil;
import com.neardrug.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Api(tags = "用户")
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public Result save(@RequestBody UserDTO userDTO){
        userService.save(userDTO);
        return Result.success();
    }

    @ApiOperation("用户登陆")
    @PostMapping("/login")
    public Result login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("用户信息:{}",userLoginDTO);

        User user=userService.login(userLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .email(user.getEmail())
                .name(user.getName())
                .token(token)
                .build();

        //在onlineusermanager中添加数据
        OnlineUserManager.userLogin(user.getId());
        return Result.success(userLoginVO);
    }

    @PutMapping("/reset")
    @ApiOperation("用户忘记密码")
    public Result resetPassword(@RequestBody UserResetDTO userResetDTO){
        userService.reset(userResetDTO);
        return Result.success();
    }

    @PostMapping("/logout")
    @ApiOperation("用户退出")
    public Result logout() {
        //移除onlineusermanager中的数据
        OnlineUserManager.userLogout();
        return Result.success();
    }
}
